package com.bbms.controller.index;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bbms.entity.ErrorCode;
import com.bbms.entity.Result;
import com.bbms.entity.SuccessCode;
import com.bbms.entity.User;
import com.bbms.service.UserService;

/**
 * @author Administrator
 * 首页控制器
 */
@Controller
@RequestMapping("/bbms/index")
public class IndexController {
	
	@Resource(name="UserServiceImpl")
	UserService us;
	
	@RequestMapping("/index")
	public String index(){
		return "/index/index.jsp";
	}
	
	@RequestMapping(value="/loginOut", method=RequestMethod.GET)
	public void loginOut(HttpServletRequest request, HttpServletResponse response) throws Exception{
		HttpSession session = request.getSession();
		session.removeAttribute("user");
		session.removeAttribute("authority");
		response.sendRedirect(request.getContextPath() + "/");
	}
	
	@RequestMapping("/userCenter")
	public void userCenter(HttpServletRequest request, HttpServletResponse reponse) throws Exception{
		String account = (String) request.getSession().getAttribute("user");
		List<?> list = us.queryByAccount(account);
		request.setAttribute("userInfo", list);
		request.getRequestDispatcher("/WEB-INF/BBMS/content/index/userCenter.jsp").forward(request, reponse);
	}
	
	@ResponseBody
	@RequestMapping("/userCenter/info")
	public List<?> userMessage(HttpServletRequest request){
		String account = (String) request.getSession().getAttribute("user");
		List<?> list = us.queryByAccount(account);
		
		return list;
		
	}
	
	@ResponseBody
	@RequestMapping("/userCenter/update")
	public Result updateUser(@ModelAttribute("user") User user, HttpServletRequest request){
		Result rs = new Result();
		try{
			user.setAccount((String)request.getSession().getAttribute(("user")));
			us.updateUser(user);
			rs.setStatus(SuccessCode.updateSuccess.getCode());
			rs.setMsg(SuccessCode.updateSuccess.getName());
			
		} catch(Exception e){
			rs.setStatus(ErrorCode.updateFailed.getCode());
			rs.setMsg(ErrorCode.updateFailed.getName());
			
		}
		
		return rs;
	}
}
